<template>
  <!-- 新建，编辑产品类型 - 产品关联物料组件 -->
  <div class="form-related-material">
    <biz-form-remote-select
      :field="field"
      :placeholder="$t('product.component.formRelatedMaterial.text1')"
      v-model="materialValue"
      :cleared="true"
      :remote-method="remoteMethod"
      @input="updateMaterial"
      value-key="id"
    >
      <div slot="option" slot-scope="{ option }">
        <div class="material-item">
          <span class="material-item-text">
            <label>{{$t('common.form.preview.materialReturn.tableLabel1')}}：</label>
            <span>{{ option.name }}</span>
          </span>
          <span class="material-item-text">
            <label>{{$t('common.form.preview.materialReturn.tableLabel2')}}：</label>
            <span>{{ option.sn }}</span>
          </span>
          <span class="material-item-text">
            <label>{{$t('common.form.preview.materialReturn.tableLabel4')}}：</label>
            <span>{{ option.property }}</span>
          </span>
        </div>
      </div>
    </biz-form-remote-select>
  </div>
</template>

<script>
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
import Platform from '@src/util/platform.ts';

// API
import { getMaterialList } from '@src/api/WareHouseApi';

export default {
  name: 'form-related-material-build',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      materialValue: this.value,
    };
  },
  computed: {},
  watch: {
    value: {
      handler(newValue) {
        if (!newValue) return;

        this.materialValue = newValue;
      },
      immediate: true,
    },
  },
  methods: {
    // 搜索物料
    async remoteMethod(params) {
      try {
        let res = await getMaterialList({
          property: '整机',
          ...params,
        });

        if (!res.success) return Platform.toast(res.message, 'error');

        res.data.list = (res.data.list || []).map(item => {
          return Object.freeze({
            label: item?.name || '',
            value: item?.id || '',
            ...item,
          });
        });

        return res.data;
      } catch (error) {
        console.warn('产品类型关联物料remoteMethod', error);
      }
    },
    // 数组扁平化  - 打平
    flatten(arr) {
      if (!arr.length) return;

      let res = [];
      arr.map(item => {
        let { children, ...other } = item;

        res.push(other);

        if (Array.isArray(children)) {
          res = res.concat(this.flatten(children));
        }
      });
      return res;
    },
    // 更新
    updateMaterial(value) {
      // 更新数据
      this.inputForValue(
        value.map(item => {
          let { id, name } = item;
          return {
            id,
            name,
          };
        })
      );

      // 切换产品关联物料清空物料清单的数据
      this.$set(this.formValue, 'productMaterialsBill', []);

      if (!value.length) return;

      // 选中物料更新物料清单
      getMaterialList({
        bomMaterialFlag: true,
        ids: [value[0].id],
        maxLevel: 3
      }).then(res => {
        if (!res.success || !res.data?.list?.length)
          return Platform.toast(res.message, 'error');

        // 关联物料下面的子物料 
        // let childrenMaterialList = this.flatten(res.data?.list).filter(item => {
        //   return item.id !== value[0].id;
        // });

        // 华大基因需求修改: 展示树形结构 最多展示两级
        const childrens = res.data?.list[0]?.children || [];

        this.$set(this.formValue, 'productMaterialsBill', childrens);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.material-item {
  padding: 10px 0;
  &-text {
    display: flex;
  }
}
</style>
